package mnnu.ghbe.service;

import mnnu.ghbe.entity.User;
import mnnu.ghbe.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    public User saveOrUpdateUser(User user) {
        // 根据openid查找用户是否存在
        Optional<User> existingUser = userRepository.findByOpenid(user.getOpenid());
        if (existingUser.isPresent()) {
            // 如果用户存在，则更新信息
            User updateUser = existingUser.get();
            updateUser.setNickname(user.getNickname());
            updateUser.setAvatar(user.getAvatar());
            return userRepository.save(updateUser);
        } else {
            // 如果用户不存在，则创建新用户
            return userRepository.save(user);
        }
    }
    
    public Optional<User> getUserByOpenid(String openid) {
        return userRepository.findByOpenid(openid);
    }
    
    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }
}